const config = require('config');
const axios = require('axios');
const qs = require('qs');
const { connectAndInsert } = require('../../model/mysql');
const createPage = require('../../reptile/Puppeteer/Puppeteer');
const log4js = require('../../reptile/Puppeteer/log/log4js.config');
const logger = log4js.getLogger("♦每日巡检");
const Mailer = require('../../reptile/QQEMail/mailer');

async function GetWEB_PUBGM_OF(URL) {
  const data = {
    gid: '', // 空留字段
    game: "PUBGM", // 游戏名称
    textContent: '新版本直链下载：', // 原文
    texHtml: '', // html
    mediaUrls: [], // 图片素材
    originalUrl: URL,
    created_at: new Date()
  };

  const { globalBrowser, page } = await createPage();
  try {
    await page.goto(URL, { timeout: 0 });
    const result = await processPageData(page);
    console.log(result);
    // return
    data.texHtml = result
    connectAndInsert('666', '667', data)
      .then(async (returnValue) => {
        console.log('返回值:', returnValue);
        // 其他操作...
        if (returnValue == '0') {
          console.log('数据库插入成功')
          const mailer = new Mailer();
          function createHtmlTable(data) {
            let html = `<table style="width:100%; border: 1px solid #ddd; border-collapse: collapse;">
                          <tr>
                            <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Link</th>
                            <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Description</th>
                          </tr>`;
        
            data.forEach(item => {
                html += `<tr>
                           <td style="border: 1px solid #ddd; padding: 8px;"><a href="${item.href}">${item.href}</a></td>
                           <td style="border: 1px solid #ddd; padding: 8px;">${item.text}</td>
                         </tr>`;
            });
        
            html += `</table>`;
            return html;
        }        
          const htmlContent = createHtmlTable(data.texHtml);
          mailer.sendMail('2622011721@qq.com', 'PUBGM有更新！', '', htmlContent)
            .then(response => console.log('Email sent successfully'))
            .catch(error => console.error('Failed to send email:', error));

          // await PostArticle(id, querid, data.texHtml, Array.isArray(data.imgUrls) ? data.imgUrls.join(',') : data.imgUrls);
        } else if (returnValue == '1') {
          console.log('数据库已存在数据')
        } else {
          console.log('数据库失败')
        }
      })
      .catch(error => {
        console.error('发生错误:', error);
      });



    return result; // 直接返回结果
  } catch (error) {
    logger.error('爬取失败:', error);
  } finally {
    await page.close();
    const pages = await globalBrowser.pages();
    logger.info('当前浏览器标签页数量：', pages.length);
  }
}

async function processPageData(page) {
  const url = page.url();
  logger.info('当前 URL 是：', url);

  try {
    const selector = '.download-wrap';
    await page.waitForSelector(selector);
    const links = await page.$$eval(selector + ' a', anchors => anchors.map(anchor => ({
      href: anchor.href,
      text: anchor.innerText.replace(/\s+/g, ' ').trim() // 清除多余的空格并整理文本
    })));


    return links;
  } catch (error) {
    logger.error('操作失败:', error);
    throw error; // 重新抛出错误以便于调用方处理
  }
}

// GetWEB_PUBGM_OF('https://www.pubgmobile.com/en-US/home.shtml');
module.exports = GetWEB_PUBGM_OF;




